這是 reverse linked list 的進階題
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
p = dummy
for i in range(left - 1):
p = p.next
prev = p
curr = p.next
tail = curr
for i in range(right - left + 1):
next = curr.next
curr.next = prev
prev = curr
curr = next
p.next = prev
tail.next = curr
return dummy.next